import { login, getDepartmentById } from '@/api/user'  // 导入用户信息相关接口
import { getToken, setToken, removeToken } from '@/utils/auth'
import parseJwt from '@/utils/Base64Util';

const user = {
  namespaced: true,

  state: {
    name: '',
    avatar: '',
    token: getToken('Token'),
    roles: [],
    introduction: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    login({commit}, userInfo) {
      localStorage.clear();
      const { username, password, type } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password, type}).then(response => {
          const { data } = response;
          localStorage.setItem('at', data.access_token);
          localStorage.setItem('rt', data.refresh_token);
          localStorage.setItem('ei', data.expires_in);
          localStorage.setItem('gat', `${new Date().getTime()}`);
          //解析jwt
          const userInfo = parseJwt(response.data.access_token);
          if(userInfo.deptId){
            localStorage.setItem('deptId', userInfo.deptId);
            localStorage.setItem('userName', userInfo.userName);
            getDepartmentById({deptId: userInfo.deptId}).then(response => {
              if(response.success){
                const { data } = response;
                sessionStorage.setItem('current_dept_name', data.name);
              }
            })
          }
          commit('SET_TOKEN', data.access_token);
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },

    //登出
    logout({}) {
      localStorage.clear();
      sessionStorage.clear();
    }
  }
}

export default user;
